package com.zan.t1;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Arrays;
import java.util.List;

/**
 * @Author Zan
 * @Create 2024/3/5 16:56
 * @Description : 演示第三方接口导致的栈内存溢出问题
 */
// json 数据转换
public class Demo1_19 {
    public static void main(String[] args) throws JsonProcessingException {
        Dept d = new Dept();
        d.setName("Market");

        Emp e1 = new Emp();
        e1.setName("zhang");
        e1.setDept(d);

        Emp e2 = new Emp();
        e2.setName("li");
        e2.setDept(d);

        d.setEmps(Arrays.asList(e1, e2));

        /*
         d: {
                name: 'Market',
                emps: [
                    {
                        name: 'zhangsan',
                        dept: {
                            name: 'Market',
                            emps: [ 递归循环导致报错 ]
                        }
                    }
                ]
            }
         */
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(d));
    }
}

class Emp { // 员工

    private String name;

    @JsonIgnore // 员工遇到部门属性就不进行转换json了，只有部门进行转化，员工不转化，以防出现循环递归
    private Dept dept;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Dept getDept() {
        return dept;
    }

    public void setDept(Dept dept) {
        this.dept = dept;
    }
}

class Dept { // 部门

    private String name;

    private List<Emp> emps;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Emp> getEmps() {
        return emps;
    }

    public void setEmps(List<Emp> emps) {
        this.emps = emps;
    }
}
